package com.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.BookMapper;
import com.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class BookController {

    @Autowired
    BookMapper bookMapper;

    //分页
    @RequestMapping("/books/{page}/{size}")
    public PageInfo<Book> findBooks(@PathVariable String page, @PathVariable String size){
        //当前页总数
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(size));
        List<Book> books = bookMapper.findBooks();
        PageInfo<Book> pageInfo = new PageInfo<>(books);
        return pageInfo;
    }

    @PostMapping("/book/add")
    public String addBook(@RequestBody Book book){
        try {
            bookMapper.addBook(book);
            return "success";
        }catch (Exception e){
            return "error";
        }
    }

    @PostMapping("/book/updateBook")
    public String updateBook(@RequestBody Book book){
        try {
            bookMapper.updateBook(book);
            return "success";
        }catch (Exception e){
            return "error";
        }
    }

    @GetMapping("/book/name/{bookName}")
    public PageInfo<Book> findBookByBookName( @PathVariable String bookName){
        List<Book> list = bookMapper.findBookByBookName(bookName);
        PageInfo<Book> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
    @GetMapping("/book/author/{author}")
    public PageInfo<Book> findBookByAuthor( @PathVariable String author){
        List<Book> list = bookMapper.findBookByAuthor(author);
        PageInfo<Book> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
    @PostMapping("/book/deleteBook/{isbn}")
    public String deleteBook( @PathVariable String isbn){
        try {
            System.out.println(isbn);
            int i = bookMapper.deleteBook(isbn);
            System.out.println(i);
            return "success";
        }catch (Exception e){
            return "error";
        }
    }

}
